package com.example.guavaSrudy.BasicEvent.better;

import com.example.guavaSrudy.BasicEvent.simple.TradeAccount;
import com.example.guavaSrudy.BasicEvent.simple.TradeAccountEvent;
import com.example.guavaSrudy.BasicEvent.simple.TradeType;
import com.google.common.eventbus.DeadEvent;
import com.google.common.eventbus.EventBus;

import java.util.Date;
import java.util.Objects;

public class BuySellTradeExecutor {

    private EventBus eventBus;

    public BuySellTradeExecutor(EventBus eventBus) {
        this.eventBus = eventBus;
    }

    public void executeTrade(TradeAccount tradeAccount,double amount, TradeType tradeType) {
        TradeAccountEvent tradeAccountEvent = processTrade(tradeAccount,amount,tradeType);
        eventBus.post(tradeAccountEvent);
    }

    private TradeAccountEvent processTrade(TradeAccount tradeAccount, double amount, TradeType tradeType) {
        Date executionTime = new Date();
        String message = String.format("processed trade for %s of amount %s \n type %s @%s",tradeAccount,amount,tradeType
        ,executionTime);
        TradeAccountEvent tradeAccountEvent;
        BuyEvent buyEvent = new BuyEvent(amount, executionTime, tradeAccount);
        SellEvent sellEvent = new SellEvent(amount, executionTime, tradeAccount);
        if(tradeType.equals(TradeType.BUY)) {
            tradeAccountEvent = buyEvent;
            DeadEvent deadEvent = new DeadEvent(eventBus, sellEvent);
            eventBus.post(deadEvent);
        }else {
            tradeAccountEvent = sellEvent;
            DeadEvent deadEvent = new DeadEvent(eventBus, buyEvent);
            eventBus.post(deadEvent);
        }
        System.out.println(message);
        return tradeAccountEvent;
    }
}
